/**
 * Copyright (C), 2019-2023,
 * FileName: FeignConfig
 * Author:   fanxquer
 * Date:     2023/7/6 10:23
 * Description: Feigin配置
 * History:
 * <author>          <time>          <version>          <desc>
 * 邱富康           2023/7/6           1.0
 */
package com.hsteach.framework.feign.client;

import com.hsteach.common.core.domain.model.AuthInfo;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

import java.util.Map;

/**
 * 〈Feigin配置〉
 *
 * @author Qiu Fukang
 * @create 2023/7/6
 * @since 1.0.0
 */

public class FeignConfig implements RequestInterceptor {

    public static ThreadLocal<Map<String, String>> contact = new ThreadLocal<>();

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (requestTemplate.url().contains("/service/isbmp/person/open/getPersonByPersonIds")){
            return;
        }
        if ("anonymousUser".equals(SecurityUtils.getAuthentication().getPrincipal())) {
            Map<String, String> map = contact.get();
            if (map != null && map.containsKey("token")) {
                requestTemplate.header("token", map.get("token"));
            }
            if (map != null && map.containsKey("orgCode")) {
                requestTemplate.header("orgCode", map.get("orgCode"));
            }
            return;
        }
        String xgkToken = SecurityUtils.getAuthInfo().getXgkToken();
        String orgCode = SecurityUtils.getAuthInfo().getOrgCode();
        if (StringUtils.isNotEmpty(xgkToken)) {
            requestTemplate.header("token", SecurityUtils.getAuthInfo().getXgkToken());
        }
        if (StringUtils.isNotEmpty(orgCode)) {
            requestTemplate.header("orgCode", SecurityUtils.getAuthInfo().getOrgCode());
        }
    }

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}